package com.maxlen.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maxlen.common.constant.ProductConstant;
import com.maxlen.common.utils.Constant;
import com.maxlen.common.utils.CopyUtils;
import com.maxlen.common.utils.PageUtils;
import com.maxlen.common.utils.Query;
import com.maxlen.goods.dao.*;
import com.maxlen.goods.entity.*;
import com.maxlen.goods.entity.dto.AttrDTO;
import com.maxlen.goods.entity.dto.AttrInfoDTO;
import com.maxlen.goods.entity.vo.AttrVO;
import com.maxlen.goods.entity.vo.ProductAttrValueVO;
import com.maxlen.goods.service.AttrAttrgroupRelationService;
import com.maxlen.goods.service.AttrService;
import com.maxlen.goods.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();
        String key = params.get(Constant.KEY) == null ? null : params.get(Constant.KEY).toString();
        if(StringUtils.hasText(key)) {
            wrapper.like(AttrEntity::getAttrId, key).or()
                    .like(AttrEntity::getAttrName, key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId, String attrType) {
        IPage<AttrEntity> page  = null;
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();

        // attrType = 1 是基本属性
        // attrType = 0 是销售属性
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMsg().equals(attrType)){
            wrapper.eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }else{
            wrapper.eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }

        String key = params.get(Constant.KEY) == null ? null : params.get(Constant.KEY).toString();
        if(StringUtils.hasText(key)) {
            wrapper.like(AttrEntity::getAttrId, key).or()
                    .like(AttrEntity::getAttrName, key);
        }

        // catId 为 0 搜索全部
        if(!catId.equals(0L)){
            wrapper.eq(AttrEntity::getCatelogId, catId);
        }
        page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrDTO> attrDTOList = records.stream().map(attrEntity -> {
            AttrDTO attrDto = CopyUtils.copy(attrEntity, AttrDTO.class);

            // 根据属性 id 在关联表中获取 分组 id
            // 根据分组 id 得到分组名
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrDto.getAttrId()));
            if (!ObjectUtils.isEmpty(relationEntity)) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if(!ObjectUtils.isEmpty(attrGroupEntity)){
                    attrDto.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            // 根据分类 id 获取分类名
            CategoryEntity categoryEntity = categoryDao.selectById(attrDto.getCatelogId());
            if (!ObjectUtils.isEmpty(categoryEntity)) {
                attrDto.setCatelogName(categoryEntity.getName());
            }

            return attrDto;
        }).collect(Collectors.toList());

        pageUtils.setList(attrDTOList);
        return pageUtils;
    }

    @Override
    @Transactional
    public void saveDetail(AttrVO attrVO) {
        AttrEntity attrEntity = CopyUtils.copy(attrVO, AttrEntity.class);
        baseMapper.insert(attrEntity);

        // 添加属性和分组关联表的信息
        // 销售属性不需要添加
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
            Long attrGroupId = attrVO.getAttrGroupId();
            if(attrGroupId != null){
                AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                entity.setAttrId(attrEntity.getAttrId());
                entity.setAttrGroupId(attrVO.getAttrGroupId());
                attrAttrgroupRelationService.save(entity);
            }
        }
    }

    @Override
    @Transactional
    public void updateDetail(AttrVO attrVO) {
        AttrEntity attrEntity = CopyUtils.copy(attrVO, AttrEntity.class);
        baseMapper.updateById(attrEntity);

        // 修改属性和分组关联表的信息
        // 销售属性不需要修改
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
            Long attrGroupId = attrVO.getAttrGroupId();
            if(attrGroupId != null){
                attrAttrgroupRelationService.updateAttrgroup(attrVO.getAttrId(), attrGroupId);
            }
        }
    }

    @Override
    public AttrInfoDTO getDetailById(Long attrId) {
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        AttrInfoDTO attrInfoDto = CopyUtils.copy(attrEntity, AttrInfoDTO.class);

        // 设置分类id
        Long[] pathById = categoryService.findPathById(attrEntity.getCatelogId());
        attrInfoDto.setCatelogPath(pathById);

        // 设置分组id
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrInfoDto.getAttrId()));
            if(!ObjectUtils.isEmpty(relationEntity)){
                attrInfoDto.setAttrGroupId(relationEntity.getAttrGroupId());
            }
        }

        return attrInfoDto;
    }

    @Override
    @Transactional
    public void removeDetail(List<Long> attrId) {
        if(!attrId.isEmpty()){
            baseMapper.deleteBatchIds(attrId);

            // 删除属性和分组关联的数据
            attrAttrgroupRelationService.removeDetailByAttrId(attrId);

        }
    }

    @Override
    public List<Long> getAttrByIdAndSearchType(List<Long> attrIdList) {
        return baseMapper.getAttrByIdAndSearchType(attrIdList);
    }

}
